<?php

namespace App\Http\Exports;

use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use App\Model\Base;

class QueryExportSailList implements FromQuery,WithHeadings,WithMapping
{

    use Exportable;

    public function __construct($param)
    {
        $map = [];
        if(!empty($param['corp_id'])){
            $map['uo.corp_id'] = $param['corp_id'];
        }
        if(!empty($param['category'])){
            $map['uo.shop_id'] = $param['shop_id'];
        }
        if(!empty($param['no_money'])){
            $map['uo.state'] = 1;
        }
        $this->map = $map;
    }

    public function query()
    {
        return Base::query()->from('user_order_detailed as o')
            ->leftJoin('goods_master as gf','gf.goods_id','=','o.goods_id')
            ->leftJoin('user_order as uo','uo.order_id','=','o.order_id')
            ->leftJoin('inout_log as io','io.goods_id','=',DB::raw("o.goods_id and io.order_id=o.order_id"))
            ->select(DB::raw('o.order_id,o.goods_num,o.goods_name,o.goods_price,o.color,o.size,gf.category_id,gf.goods_code,uo.create_time,uo.add,uo.corp_id,uo.shop_id,io.num'))
            ->orderBy('o.order_id')
            ->where($this->map);
    }

    public function headings(): array
    {
        return [
          '注文番号',
          '注文の時間',
          '依赖元',
          '納品先',
          '発送先',
          'カテゴリー',
          '商品名',
          'カラー/サイズ',
          '購入数量',
          '出荷数',
          '価格',
        ];
    }

    public function map($invoice):array
    {
        return [
            $invoice->order_id,
            $invoice->create_time,
            fun_corp($invoice->corp_id),
            fun_shop($invoice->shop_id),
            $invoice->add,
            fun_category($invoice->category_id),
            $invoice->goods_name,
            $invoice->color.'/'.$invoice->size,
            $invoice->goods_num,
            $invoice->num,
            $invoice->num*$invoice->goods_price,

        ];
    }

}
